package site.isscloud.project.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import site.isscloud.project.domain.PjAlarmRecord;
import site.isscloud.project.mapper.PjAlarmRecordMapper;
import site.isscloud.project.service.IPjAlarmRecordService;
import site.isscloud.project.service.IPjAlarmEventService;

import java.util.Date;
import java.util.List;

/**
 * 告警记录Service业务层处理
 */
@Service
public class PjAlarmRecordServiceImpl implements IPjAlarmRecordService {

    private static final Logger log = LoggerFactory.getLogger(PjAlarmRecordServiceImpl.class);
    private static final Logger alarmLog = LoggerFactory.getLogger("alarm");

    @Autowired
    private PjAlarmRecordMapper pjAlarmRecordMapper;

    @Autowired
    private IPjAlarmEventService pjAlarmEventService;

    /**
     * 查询告警记录
     */
    @Override
    public PjAlarmRecord selectPjAlarmRecordById(Long id) {
        return pjAlarmRecordMapper.selectPjAlarmRecordById(id);
    }

    /**
     * 查询告警记录列表
     */
    @Override
    public List<PjAlarmRecord> selectPjAlarmRecordList(PjAlarmRecord pjAlarmRecord) {
        return pjAlarmRecordMapper.selectPjAlarmRecordList(pjAlarmRecord);
    }

    /**
     * 新增告警记录
     */
    @Override
    @Transactional
    public int insertPjAlarmRecord(PjAlarmRecord pjAlarmRecord) {
        pjAlarmRecord.setCreateTime(new Date());
        if (pjAlarmRecord.getState() == null) {
            pjAlarmRecord.setState(0); // 默认未处理状态
        }
        int result = pjAlarmRecordMapper.insertPjAlarmRecord(pjAlarmRecord);

        alarmLog.info("新增告警记录 - ID: {}, 设备: {}, 通道: {}, 类型: {}, 米标: {}",
                pjAlarmRecord.getId(), pjAlarmRecord.getDeviceNo(),
                pjAlarmRecord.getChanel(), pjAlarmRecord.getAlarmType(),
                pjAlarmRecord.getMeterMark());

        return result;
    }

    /**
     * 修改告警记录
     */
    @Override
    public int updatePjAlarmRecord(PjAlarmRecord pjAlarmRecord) {
        return pjAlarmRecordMapper.updatePjAlarmRecord(pjAlarmRecord);
    }

    /**
     * 批量删除告警记录
     */
    @Override
    public int deletePjAlarmRecordByIds(Long[] ids) {
        return pjAlarmRecordMapper.deletePjAlarmRecordByIds(ids);
    }

    /**
     * 删除告警记录信息
     */
    @Override
    public int deletePjAlarmRecordById(Long id) {
        return pjAlarmRecordMapper.deletePjAlarmRecordById(id);
    }

    /**
     * 处理MQTT告警消息
     */
    @Override
    @Transactional
    public void processMqttAlarmMessage(PjAlarmRecord alarmRecord) {
        try {
            alarmLog.info("开始处理MQTT告警消息 - 设备: {}, 通道: {}, 类型: {}",
                    alarmRecord.getDeviceNo(), alarmRecord.getChanel(), alarmRecord.getAlarmType());

            // 1. 保存告警记录
            int insertResult = insertPjAlarmRecord(alarmRecord);
            if (insertResult <= 0) {
                alarmLog.error("保存告警记录失败 - 设备: {}, 通道: {}",
                        alarmRecord.getDeviceNo(), alarmRecord.getChanel());
                return;
            }

            // 2. 处理告警事件关联
            pjAlarmEventService.processAlarmRecord(alarmRecord);

            alarmLog.info("MQTT告警消息处理完成 - 记录ID: {}", alarmRecord.getId());

        } catch (Exception e) {
            alarmLog.error("处理MQTT告警消息失败 - 设备: {}, 通道: {}, 错误: {}",
                    alarmRecord.getDeviceNo(), alarmRecord.getChanel(), e.getMessage(), e);
            throw new RuntimeException("处理MQTT告警消息失败", e);
        }
    }

    /**
     * 批量更新告警记录状态
     */
    @Override
    public int updateAlarmRecordStateBatch(List<Long> ids, Integer state) {
        if (ids == null || ids.isEmpty()) {
            return 0;
        }
        int result = pjAlarmRecordMapper.updateAlarmRecordStateBatch(ids, state);
        alarmLog.info("批量更新告警记录状态 - 记录数: {}, 新状态: {}, 成功数: {}",
                ids.size(), state, result);
        return result;
    }

    /**
     * 查询指定时间范围内的告警记录
     */
    @Override
    public List<PjAlarmRecord> selectAlarmsByTimeRange(Date startTime, Date endTime, Integer alarmType) {
        alarmLog.debug("查询时间范围内告警记录 - 开始时间: {}, 结束时间: {}, 告警类型: {}",
                startTime, endTime, alarmType);
        return pjAlarmRecordMapper.selectAlarmsByTimeRange(startTime, endTime, alarmType);
    }

    /**
     * 根据设备、通道、米标和时间范围查询活跃告警
     * @param deviceNo 设备编号
     * @param channel 通道号
     * @param meterMark 米标
     * @param startTime 开始时间（可选）
     * @param endTime 结束时间（可选）
     */
    @Override
    public List<PjAlarmRecord> selectActiveAlarmsByDeviceChannelMeter(String deviceNo, Integer channel, Integer meterMark, Date startTime, Date endTime) {
        return pjAlarmRecordMapper.selectActiveAlarmsByDeviceChannelMeter(deviceNo, channel, meterMark, startTime, endTime);
    }
}